/* eslint-disable react/jsx-props-no-spreading */
import { messages } from "share/common";
import React from "react";
import { connect } from "react-redux";
import moment from "moment";
import {
  Form,
  Input,
  Switch as Radio,
  InputNumber,
  Button,
  Icon,
  Select,
  message,
  Spin,
  Tooltip,
} from "antd";
import "styles/receipt-type-setting/contract-type-define/new-contract-type.scss";
import DateRangePicker from "components/date-range-picker";
import service from "./service";
import { classifyTypeOptions } from "./config";
import errorMessage from 'share/errorMessage';

const FormItem = Form.Item;
const { Option } = Select;

class SimpleTextValue extends React.Component {
  render() {
    return <div>{this.props.value || ""}</div>;
  }
}

class ExpenseAmountRuleForm extends React.Component {
  constructor(props) {
    super(props);
    const { classifyType, cycle, quatoId } = props.params;

    const currentClassifyType =
      classifyTypeOptions.find((item) => item.value === classifyType) || {};

    this.state = {
      currentClassifyType,
      loading: false,
    };
  }

  componentDidMount() {
    const record = this.props.params.record;
    if (record) {
      this.setFieldsValue(record);
    }
  }

  componentDidUpdate(prevProps) {
    const record = this.props.params.record;
    const prevRecord = prevProps.params.record;
    if (record && (!prevRecord || record.id !== prevRecord.id)) {
      this.setFieldsValue(record);
    }
  }

  setFieldsValue = (record) => {
    let dateRange = [];
    if (record.startTime && record.endTime) {
      dateRange = [
        moment(new Date(record.startTime)),
        moment(new Date(record.endTime)),
      ];
    } else if (record.startTime) {
      dateRange = [
        moment(new Date(record.startTime)),
      ];
    }
    const name = record.name;
    const amount = record.amount;
    // const isControl = !!record.isControl;
    const fieldsValue = {
      dateRange,
      isControl: true,
      amount,
      name,
    };
    // console.log(fieldsValue);
    this.props.form.setFieldsValue(fieldsValue);
  };

  // 更新保存
  handleUpdate = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll(async (err, values) => {
      if (err) return;
      try {
        const { id, quatoId, pkId } = this.props.params.record;
        const { amount, dateRange } = values;
        const params = {
          id,
          quatoId,
          pkId,
          isControl: true,
          amount,
        };
        if (Array.isArray(dateRange)) {
          if (dateRange[0]) {
            params.startTime = dateRange[0].format("YYYY-MM-DD");
          } else {
            throw new Error('生效时间段的起始日期是必填项'); 
          }
          if (dateRange[1]) params.endTime = dateRange[1].format("YYYY-MM-DD");
        } else {
          throw new Error('生效时间段的起始日期是必填项'); 
        }
        const res = await service.modifyDetail(params);
        if (res.status !== 200) {
          throw new Error(res || "保存失败");
        }
        this.props.close(true);
      } catch (e) {
        if (e.response) {
          errorMessage(e.response);
          return;
        }
        message.error(e.message);
      }
    });
  };

  // 取消
  handleCancel = () => {
    this.props.close();
  };

  render() {
    const { loading, data, currentClassifyType } = this.state;
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 10, offset: 1 },
    };
    return (
      <div className="new-contract-type">
        <Form onSubmit={this.handleUpdate}>
          <FormItem {...formItemLayout} label="额度">
            {getFieldDecorator("amount", {
              rules: [
                {
                  required: true,
                  message: messages("common.please.input"),
                },
              ],
            })(
              <InputNumber
                placeholder={messages("common.please.enter")}
                step="0.01"
                formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                parser={value => value.replace(/\$\s?|(,*)/g, '')}
              />
            )}
          </FormItem>

          <FormItem {...formItemLayout} label="生效时间段">
            {getFieldDecorator("dateRange", {
              rules: [
                {
                  required: false,
                  message: messages("common.please.select"),
                },
              ],
            })(<DateRangePicker />)}
          </FormItem>

          {/* <FormItem {...formItemLayout} label="是否管控">
            {getFieldDecorator("isControl", {
              valuePropName: "checked",
              rules: [
                {
                  required: true,
                  message: messages("common.please.select")
                },
              ],
              initialValue: true,
            })(<Radio />)}
          </FormItem> */}
          <FormItem {...formItemLayout} label={currentClassifyType.title}>
            {getFieldDecorator("name", {
              rules: [
                {
                  required: true,
                },
              ],
            })(<SimpleTextValue />)}
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>
              {messages("common.save")}
            </Button>
            <Button onClick={this.handleCancel}>
              {messages("common.cancel")}
            </Button>
          </div>
        </Form>
      </div>
    );
  }
}

ExpenseAmountRuleForm.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    main: state.main,
  };
}

const wrappedExpenseAmountRuleForm = Form.create()(ExpenseAmountRuleForm);

export default connect(mapStateToProps, null, null, { withRef: true })(
  wrappedExpenseAmountRuleForm
);
